package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 获取静态资源工具类
 */
public class StaticResouceUtil {

    /**
     * 获取静态资源文件的绝对路径
     * @param path
     * @return
     */
    public static String getAbsolutePath (String path) {
        String absolutePath = StaticResouceUtil.class.getResource("/").getPath();
        return absolutePath.replaceAll("\\\\", "/") + path;
    }

    /**
     * 读取静态文件输入流， 通过输出流输出
     * @param inputStream
     * @param outputStream
     */
    public static void outputStaticSource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }

        int resouceSize = count;
        //输出http请求头， 然后在输出其具体内容
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resouceSize).getBytes());

        //读取内容输出
        long written = 0; // 已经读取的内容长度
        int byteSize = 1024; //计划每次缓冲的长度
        byte[] bytes = new byte[byteSize];

        while (written < resouceSize) {
            if (written + byteSize > resouceSize) { // 说明剩余未读取大小不足一个1024byte， 那就按真是长度处理
                byteSize = (int) (resouceSize - written); // 剩余的文件长度
                bytes = new byte[byteSize];
            }
            inputStream.read(bytes);
            outputStream.write(bytes);

            outputStream.flush();
            written += byteSize;
        }
    }
}
